rm(list=ls())
library(BMS)
library(metafor)
set.seed(12345)
PATH="C:/Users/hong_/Desktop/World Development/FinalCodes_Data/"

# Loading Dataset
DT<-as.data.frame(read.csv(paste(PATH, 'data_sorted.csv', sep='')))

# Random Model Estimation RE(w/SE)
regRE <- rma.uni(pcc ~ 1 , vi=sepcc*sepcc, method='ML', data=DT)

# Computing weights
EstWeight <- 1/sqrt((regRE$tau2 + DT$sepcc^2))

# Getting data for (weighted) Baysian Modeling Averaging Estimation
ESTDATA<- cbind.data.frame( DT[, c("pcc","fdilog", "fdiother", 
                                   "entretype2", "entretype3", 
                                   "entreother", "oecd", "nonoecd", 
                                   "crosssection", "panelfe", 
                                   "lagdv", "busenviron", "iv", 
                                   "journal")])*EstWeight

# Estimation
BMSEstimation <- bms(ESTDATA, burn = 1000000, iter = 2000000, 
                     g = "UIP", mprior = "uniform", nmodel = 2000, mcmc = "bd", user.int = FALSE)
EstCoeff <- coef(BMSEstimation, order.by.pip = TRUE, incl.possign = TRUE, std.coefs = FALSE)

# Making Table 8
Table08 <- as.data.frame(EstCoeff[, c(2,4,1)])
Table08$`Post Mean`<- round(Table08$`Post Mean`,3);
Table08$Cond.Pos.Sign <- round(Table08$Cond.Pos.Sign,2)
Table08$PIP <- round(Table08$PIP,2)
print(Table08)
write.csv(as.data.frame(Table08), "EstimationResults/Table08.csv", row.names=TRUE)


